package com.woniuxy.consumer;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.woniuxy.entity.KillOrder;
import com.woniuxy.util.RabbitmqConst;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author dingpf
 * @version 1.0
 * @description
 * @create 2025/5/6 16:00
 *
 * 消费者重复消费问题？
 * 产生的原因：消费者正常消费完消息，通过AMQP协议给队列应答。消费者应答发出去了，但是
 *           应为网络原因队列没有收到！导致消费者重复消费。
 *
 * 解决方案：1：在发送该消息时，去消息中的唯一属性值，存入redis
 *         2: 在消费者消费消息前，去尝试是否能成功删除该唯一属性值（redis）
 *
 *
 */
@Component
public class AddKillOrderConsumer {

    @Resource
    private RedisTemplate redisTemplateInit;


    @RabbitListener(queues = RabbitmqConst.ADDKILLORDER_QUEUE)
    public void receive(String msg, Channel channel, Message message){
        try {
            //把json字符串转成对象
            KillOrder killOrder = JSON.parseObject(msg, KillOrder.class);
            //参数2：泛型.class
            //List<KillOrder> killOrders = JSON.parseArray(msg, KillOrder.class);
            Boolean delfalg = redisTemplateInit.delete(killOrder.getKillOrderNum());
            if (delfalg){
                //KillOrderMapper.addKillOrder(killOrder)
            }

            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            e.printStackTrace();
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
